export default {
    namespaced: true,
    state: {
        cartData: []
    },
    mutations: {
        SET_CART(state, payload) {

            let target = state.cartData.find(item => item.id === payload.id)

            if (!target) {
                let obj = {
                    title: payload.title,
                    price: payload.price,
                    count: 1,
                    id: payload.id
                }
                state.cartData.push(obj)
            } else {
                target.count++
            }

        }
    },
    actions: {
        ADD_CART(context, payload) {
            context.commit('SET_CART', payload)
            context.commit('product/DECREASE_INVENTORY', payload.id, { root: true })
        }
    },
    getters: {
        total(state) {
            return (state.cartData.reduce((total, item) => {
                return total += item.price * item.count
            }, 0)).toFixed(2)
        }
    }
}